// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()//引用云数据库
const account = db.collection("account")

// 云函数入口函数
// 残局函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  if (event.type == 'get') {

    const time = await account.where({
      openid: wxContext.OPENID
    })
      .field({
        tiliTime: true,
        starTime: true
      })
      .get()

    let currentSecond = Math.floor(new Date().getTime() / 1000)
    let lastSecond = Math.floor(new Date(time.data[0].tiliTime).getTime() / 1000)
    let diffSecondTiLi = 300 - (currentSecond - lastSecond)
    if (diffSecondTiLi < 0) { diffSecondTiLi = 0 }
    // 300秒    600秒
    currentSecond = Math.floor(new Date().getTime() / 1000)
    lastSecond = Math.floor(new Date(time.data[0].starTime).getTime() / 1000)
    diffSecondStar = 600 - (currentSecond - lastSecond)
    if (diffSecondStar < 0) { diffSecondStar = 0 }

    return {
      code: 'getTime:ok',
      res: {
        diffSecondTiLi,
        diffSecondStar
      }
    }

  } else {
    if (event.name == 'tili') {
      await account.where({
        openid: wxContext.OPENID
      })
        .update({
          data: {
            tiliTime: new Date()
          }
        })
    } else {
      await account.where({
        openid: wxContext.OPENID
      })
        .update({
          data: {
            starTime: new Date()
          }
        })
    }
    return {
      code: 'updateTime:ok',
      res: null
    }
  }
}
